<?php
/**
 * 发票相关接口
 */
class Action
{
    private $per_page = 20;

    /**
     * 发票列表
     * @author xiaolin
     * @date   2016-08-30
     * @return
     */
    public function index() {
        $page_no = $type = $is_urgen = $status = $search_filter = null;

        //给变量初始化一个值,如果获取到了其get值则重新赋值
        extract(URLTracker::init(array(
            'page_no' => 1,
            'type' => -1,
            //'is_urgen' => -1,
            'status' => -1,
            'search_filter' => array()
        )));

        $where = 'and 1 = 1 ';
        if (isset($search_filter['company_name']) && $search_filter['company_name']) {
            $where .= ' and i.company_name like "%' . $search_filter['company_name'] . '%"';
        }
        if (isset($search_filter['taxpayer_number']) && $search_filter['taxpayer_number']) {
            $where .= ' and i.taxpayer_number like "%' . $search_filter['taxpayer_number'] . '%"';
        }
        if (isset($search_filter['realname']) && $search_filter['realname']) {
            $where .= ' and u.realname like "%' . $search_filter['realname'] . '%"';
        }
        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $where .= ' and i.add_time >= "' . $search_filter['start_date'] . ' 00:00:00"';
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $where .= ' and i.add_time <= "' . $search_filter['end_date'] . ' 00:00:00"';
        }

        if ($type != -1) {
            $where .= ' and i.type = ' . $type;
        }
        /*
        if ($is_urgen != -1) {
            $where .= ' and i.is_urgen = ' . $is_urgen;
        }*/
        if ($status != -1) {
            $where .= ' and i.status = ' . $status;
        }
        if (!ONDEV) {
            $where .= ' and u.is_enable = 1';
        }

        $count_sql = 'select count(i.id) as num from invoice i left join `user` u on i.user_id = u.id left join invoice_courier ic on i.id = ic.invoice_id where i.is_enable = 1 and u.status = 1 ' . $where;
        $invoice_count = _model('invoice')->getAll($count_sql)[0]['num'];

        //分页配置
        $pager = new Pager($this->per_page);
        if ($pager->generate($invoice_count)) {
            Response::assign('pager', $pager);
        }

        $sql = 'select i.*, u.realname, u.mobile, ic.courier_company_name, ic.courier_number, ic.mailed_time from invoice i left join `user` u on i.user_id = u.id left join invoice_courier ic on i.id = ic.invoice_id where i.is_enable = 1 and u.status = 1 ' . $where . ' order by i.id desc ' . $pager->getLimit($page_no);
        $invoice_list = _model('invoice')->getAll($sql);

        Response::assign('type', $type);
        Response::assign('is_urgen', $is_urgen);
        Response::assign('status', $status);
        Response::assign('search_filter', $search_filter);
        Response::assign('invoice_list', $invoice_list);
        Response::display('admin/invoice_list.html');
    }

    /**
     * 确认开票
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function confirm_invoice() {
        $id = an_request('id');
        $actual_price = an_request('actual_price');
        $status = 3;

        //状态验证
        $this->change_status_validation($id, $status, 1);

        //实开金额验证
        $this->actual_price_validation($actual_price);

        _model('invoice')->update($id, array(
            'status' => $status,
            'actual_price' => format_money($actual_price),
            'update_time' => date('Y-m-d H:i:s')
        ));

        return_data(0, 'success');
    }

    /**
     * 审核通过
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function confirm_pass() {
        $id = an_request('id');
        $status = 1;

        //状态验证
        $this->change_status_validation($id, $status, 0);
        _model('invoice')->update($id, array(
            'status' => $status,
            'update_time' => date('Y-m-d H:i:s')
        ));

        return_data(0, 'success');
    }

    /**
     * 驳回
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function confirm_reject() {
        $invoice_id = an_request('id');
        $reject_remark = an_request('reject_remark', '');
        $status = 2;

        if (!$reject_remark) {
            return_data(1, '请填写驳回原因');
        }

        $this->change_status_validation($invoice_id, $status, array(0, 1));

        $success = false;
        //事务开始
        ts_helper::begin();
        try {
            ts_helper::_model('invoice')->update($invoice_id, array(
                'status' => $status,
                'reject_remark' => $reject_remark,
                'update_time' => date('Y-m-d H:i:s')
            ));

            $invoice = _model('invoice')->read($invoice_id);
            $order_ids = _model('invoice_relation')->getFields('order_id', array('invoice_id' => $invoice_id, 'status' => 1));

            //回滚订单开票状态和开票时间
            ts_helper::_model('order')->update(array('id' => $order_ids), array(
                'make_invoice_status' => 0,
                'make_invoice_time' => '0000-00-00 00:00:00'
            ));

            //设置发票订单关联表的状态为无效
            ts_helper::_model('invoice_relation')->update(array('invoice_id' => $invoice_id, 'status' => 1), array(
                'status' => 0,
                'update_time' => date('Y-m-d H:i:s')
            ));

            //回滚用户可开票额度
            $change_amount_log = json_decode($invoice['change_amount_log'], true);
            foreach ($change_amount_log as $key => $value) {
                //查询当月现有的额度
                $user_invoice_amount = _model('user_invoice_amount')->field('id', 'amount')->read(array(
                    'user_id' => $invoice['user_id'],
                    'object_type' => $invoice['object_type'],
                    'month' => $key
                ));
                //在当月的额度上增加之前扣除的额度
                ts_helper::_model('user_invoice_amount')->update($user_invoice_amount['id'], array(
                    'amount' => format_money($value + $user_invoice_amount['amount']),
                    'update_time' => date('Y-m-d H:i:s')
                ));
            }

            $success = true;
            ts_helper::commit();
        } catch (Exception $e) {
            ts_helper::trace_log($e);
            ts_helper::rollback();
        }

        if ($success) {
            $info = '驳回成功';

            $user = _uri('user', $invoice['user_id']);
            $msg_arr['name'] = $user['realname'];
            $msg_arr['date'] = substr($invoice['add_time'], 0, 10);
            $msg_arr['company'] = $invoice['company_name'];
            $msg_arr['reason'] = $reject_remark;

            $sms_res = aliysms_helper::sms_send('抱抱堂', $msg_arr, $user['mobile'], 'invoice_reject_reason');
            if (!$sms_res) {
                $info = '驳回成功,短信下发失败';
            }
            return_data(0, $info);
        } else {
            return_data(1, '驳回失败');
        }
    }

    /**
     * 发票详情
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function invoice_detail() {
        $id = an_request('id');

        if (!$id) {
            return_data(1, '请选择一条记录');
        }

        $where = '';
        if (!ONDEV) {
            $where .= ' and u.is_enable = 1';
        }

        //发票、合伙人信息、快递信息
        $sql = 'select i.*, u.realname, u.mobile, c.courier_number, c.courier_company_name, date_format(c.mailed_time, "%Y-%m-%d") as mailed_time, c.courier_remark from invoice i left join `user` u on i.user_id = u.id left join invoice_courier as c on i.id = c.invoice_id where i.is_enable = 1 and u.status = 1 ' . $where . ' and i.id = ' . $id;
        $invoice = _model('invoice')->getAll($sql);

        if (!$invoice) {
            return_data(1, '当前记录不存在');
        }
        $invoice = $invoice[0];

        //订单和所下订单的店铺信息
        $order_sql = 'select o.id as order_id, o.add_time, o.price, o.goods_num, s.title from invoice_relation as i left join `order` as o on i.order_id = o.id left join store as s on o.store_id = s.id where i.invoice_id = ' . $id;
        $order_list = _model('invoice_relation')->getAll($order_sql);

        $invoice['order_sum_price'] = 0.00;
        $invoice['order_sum_goods_num'] = 0;
        if ($order_list) {
            foreach ($order_list as $key => $value) {
                $order_list[$key]['order_no'] = order_helper::order_id_encode($value['order_id']);
                $invoice['order_sum_price'] += $value['price'];
                $invoice['order_sum_goods_num'] += $value['goods_num'];
            }
        }
        $invoice['order_sum_price'] = format_money($invoice['order_sum_price']); //格式化金钱
        $invoice['order_list'] = $order_list;


        Response::assign('invoice', $invoice);
        Response::display('admin/invoice_detail.html');
    }

    /**
     * 填写快递信息
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function create_courier() {
        $invoice_id = an_request('invoice_id', '');
        $courier_company_name = an_request('courier_company_name', '');
        $courier_number = an_request('courier_number', '');
        $mailed_time = an_request('mailed_time', '');
        $courier_remark = an_request('courier_remark', '');

        $data = array(
            'invoice_id' => $invoice_id,
            'courier_company_name' => $courier_company_name,
            'courier_number' => $courier_number,
            'mailed_time' => $mailed_time,
            'courier_remark' => $courier_remark,
            'add_time' => datetime(),
            'update_time' => datetime(),
        );

        //数据格式验证
        $this->courier_validation($data);

        //状态验证
        $status = 4;
        $this->change_status_validation($invoice_id, $status, 3);

        _model('invoice_courier')->create($data);

        _model('invoice')->update($invoice_id, array(
            'status' => $status,
            'update_time' => date('Y-m-d H:i:s')
        ));

        //发送短信提醒
        $invoice = _uri('invoice', $invoice_id);
        $user = _uri('user', $invoice['user_id']);

        $msg_arr['name'] = $user['realname'];
        $msg_arr['company'] = $invoice['company_name'];
        $msg_arr['date'] = date('m月d日', strtotime($mailed_time));
        $msg_arr['courier'] = $courier_company_name;
        $msg_arr['number'] = $courier_number;

        $sms_res = aliysms_helper::sms_send('抱抱堂', $msg_arr, $user['mobile'], 'invoice_courier_info');
        if (!$sms_res) {
            return_data(0, '邮寄信息添加成功,短信下发失败');
        }
        return_data(0, 'success');
    }

    /**
     * 修改快递单号
     * @author xiaolin
     * @date   2016-10-27
     * @return json
     */
    public function update_courier_number() {
        $invoice_id = an_request('id');
        $courier_number = an_request('courier_number');

        $data = array(
            'invoice_id' => $invoice_id,
            'courier_number' => $courier_number,
        );

        //数据格式验证
        $this->courier_validation($data);

        $invoice = _model('invoice')->field('id', 'status')->read($invoice_id);
        if (!$invoice) {
            return_data(1, '该条记录不存在');
        }

        if (4 != $invoice['status']) {
            return_data(1, '您当前的状态不是已完成,无法修改快递单号');
        }

        _model('invoice_courier')->update(array('invoice_id' => $invoice_id), array(
            'courier_number' => $courier_number,
            'update_time' => datetime()
        ));

        return_data(0, '修改成功');
    }

    /**
     * 发票信息必填及格式校验
     * @author xiaolin
     * @date   2016-08-30
     * @param array $params 要校验的数据
     * @return json
     */
    private function courier_validation($params) {
        if (!$params['invoice_id']) {
            return_data(1, '请选择一个发票记录');
        }
        if (isset($params['courier_company_name']) && !$params['courier_company_name']) {
            return_data(1, '请填写快递公司名称');
        }
        if (isset($params['courier_number']) && !$params['courier_number']) {
            return_data(1, '请填写快递单号');
        }
        if (isset($params['courier_number']) && !preg_match('/\d+/', $params['courier_number'])) {
            return_data(1, '快递单号格式不正确');
        }
        if (isset($params['mailed_time']) && !$params['mailed_time']) {
            return_data(1, '请填写邮寄时间');
        }
    }

    /**
     * 发票状态更改校验
     * @author xiaolin
     * @date   2016-08-30
     * @param int $id 发票ID
     * @param int $status 要更改的状态
     * @param int|array $validate_status 用于校验的状态
     * @return json
     */
    private function change_status_validation($id, $status, $validate_status = '') {
        if (!$id) {
            return_data(1, '请选择要更改的记录');
        }
        if (!$status && $status != 0) {
            return_data(1, '请选择要更改的状态');
        }
        if (!array_key_exists($status, invoice_config::$status)) {
            return_data(1, '状态不合法');
        }
        $invoice = _model('invoice')->field('id', 'status')->read($id);
        if (!$invoice) {
            return_data(1, '该条记录不存在');
        }
        if ($status == $invoice['status']) {
            return_data(1, '您当前的状态已经是' . invoice_config::$status[$status] . '了');
        }
        if ($validate_status || $validate_status === 0) {
            if (is_array($validate_status)) {
                if  (!in_array($invoice['status'], $validate_status)) {
                    return_data(1, '您目前状态不是' . invoice_config::$status[$validate_status] . ', 不能执行此操作');
                }
            } elseif ($invoice['status'] != $validate_status) {
                return_data(1, '您目前状态不是' . invoice_config::$status[$validate_status] . ', 不能执行此操作');
            }
        }
    }

    /**
     * 实开金额验证
     * @author xiaolin
     * @date   2016-10-26
     * @param decimal $actual_price 实开金额
     * @return json
     */
    private function actual_price_validation($actual_price) {
        if (!$actual_price || $actual_price <= 0) {
            return_data(1, '实开发票金额必填且大于0');
        }
        if (!is_numeric($actual_price)) {
            return_data(1, '实开发票金额格式不正确');
        }
    }
}